package com.apache.ius.controller;

import com.apache.api.api.ApiService;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.api.vo.ResultMsg;
import com.apache.database.constant.SpringContextLoader;
import com.apache.database.model.Page;
import com.apache.rpc.common.LoadRpcService;
import com.apache.tools.StrUtil;
import com.apache.uct.common.ToolsUtil;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * description: 请求地址进入页面统一action
 * @author xhe 创建时间：2019年03月11日
 */
@Controller
public class InfoAction extends BaseAction{

    @Autowired(required = false)
    @Qualifier("infoService")
    private ApiService infoService;

    /**
     * 统一入口方法
     */
    @RequestMapping(value = {"/info/"})
    @ResponseBody
    public Object doInvoke(HttpServletRequest request, HttpServletResponse response)  throws Exception {
        String doCode = StrUtil.doNull(request.getParameter("doCode"), "dymicSql");
        Map<String, String> paramMap = getParameterMap(request);
        log.info("parmMap-->"+paramMap);
        String uri = request.getRequestURI();
        Method method = doInvoke(this.getClass(), request, response, uri, doCode);
        try {
            if (null != method) {
                Object obj = method.invoke(this, request, response);
                return obj;
            } else {
                gotoErrorPage(request, response, "请求的Action地址未定义");
            }
        }catch (Exception e){
            log.info("执行失败(doInvoke)：", e);
            ResultMsg msg = new ResultMsg("F", "请求失败，请重试");
            JSONObject array = JSONObject.fromObject(msg);
            return array;
        }
        return null;
    }

    /**
     * 保存sortInfo
     */
    @RequestMapping(value = "/info/saveInfo", method = RequestMethod.POST)
    @ResponseBody
    public ResultMsg saveSortInfo(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        ResultMsg msg = null;
        Map<String, String> params = this.getParameterMap(request);
        params.put("method", "save");
        ParamsVo vo = new ParamsVo();
        vo.setParams(params);
        vo.setMethodKey("sortInfoAction");
        ResultEntity entity = doInfoService(vo);
        if (StrUtil.isNotNull(String.valueOf(entity.getEntity()))) {
            msg = new ResultMsg("T", String.valueOf(entity.getEntity()));
        } else {
            msg = new ResultMsg("F", entity.getMessage());
        }
        return msg;
    }

    /**
     * description:  删除sortInfo(sortId)
     */
    @RequestMapping(value = "/info/delInfo", method = RequestMethod.GET)
    @ResponseBody
    public ResultMsg delSortInfo(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        ResultMsg msg = null;
        Map<String, String> params = this.getParameterMap(request);
        params.put("method", "del");
        ParamsVo vo = new ParamsVo();
        vo.setParams(params);
        vo.setMethodKey("sortInfoAction");
        ResultEntity entity = doInfoService(vo);
        if (StrUtil.isNotNull(String.valueOf(entity.getEntity()))) {
            msg = new ResultMsg("T", String.valueOf(entity.getEntity()));
        } else {
            msg = new ResultMsg("F", entity.getMessage());
        }
        return msg;
    }

    /**
     * description:  创建数据库
     */
    @RequestMapping(value = "/info/createDatabase", method = RequestMethod.POST)
    @ResponseBody
    protected ResultMsg createDatabase(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        ResultMsg msg = new ResultMsg("F", "数据库创建失败");
        Map<String, String> params = this.getParameterMap(request);
        String useDatasource=StrUtil.doNull(params.get("useDatasource"),"plateform");
        String databaseName = params.get("databaseName");
        if(StrUtil.isNull(databaseName)){
            msg = new ResultMsg("F", "数据库名不能为空！");
            return msg;
        }
        params.put("useDatasource",useDatasource);
        params.put("method", "createDatabase");
        ParamsVo vo = new ParamsVo();
        vo.setParams(params);
        vo.setMethodKey("sortInfoAction");
        ResultEntity entity = doInfoService(vo);
        if (entity != null) {
            String entityResult = String.valueOf(entity.getEntity());
            if (StrUtil.isNotNull(entityResult) && "T".equals(entityResult)) {
                msg = new ResultMsg("T", String.valueOf(entity.getEntity()));
            } else {
                msg = new ResultMsg("F", entity.getMessage());
            }
        }
        log.info("数据库创建结果：" + msg);
        return msg;
    }


    /**
     * description:  发布表单（sortId）
     */
    @RequestMapping(value = "/info/publish", method = RequestMethod.GET)
    @ResponseBody
    public ResultMsg publish(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        ResultMsg msg = new ResultMsg("F", "启用失败");
        Map<String, String> params = this.getParameterMap(request);
        params.put("method", "publish");
        ParamsVo vo = new ParamsVo();
        vo.setParams(params);
        vo.setMethodKey("sortInfoAction");
        ResultEntity entity = doInfoService(vo);
        if (entity != null) {
            String entityResult = String.valueOf(entity.getEntity());
            if (StrUtil.isNotNull(entityResult) && "T".equals(entityResult)) {
                msg = new ResultMsg("T", String.valueOf(entity.getEntity()));
            } else {
                msg = new ResultMsg("F", entity.getMessage());
            }
        }
        log.info("数据表启用结果：" + msg);
        return msg;
    }

    /**
     * description:  停用表单（sortId）
     */
    @RequestMapping(value = "/info/stop", method = RequestMethod.GET)
    @ResponseBody
    public ResultMsg stopInfo(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        Map<String, String> params = this.getParameterMap(request);
        ResultMsg msg = null;
        params.put("method", "stop");
        ParamsVo vo = new ParamsVo();
        vo.setParams(params);
        vo.setMethodKey("sortInfoAction");
        ResultEntity entity = doInfoService(vo);
        if (StrUtil.isNotNull(String.valueOf(entity.getEntity()))) {
            msg = new ResultMsg("T", String.valueOf(entity.getEntity()));
        } else {
            msg = new ResultMsg("F", entity.getMessage());
        }
        return msg;
    }

    /**
     * description:  查询表单
     */
    @RequestMapping(value = "/info/listInfo", method = RequestMethod.GET)
    @ResponseBody
    public Object listInfo(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        Map<String, String> params = this.getParameterMap(request);
        Map<String, Object> data = new HashMap<String, Object>();
        params.put("method", "list");
        ParamsVo vo = new ParamsVo();
        vo.setParams(params);
        vo.setMethodKey("sortInfoAction");
        ResultEntity entity = doInfoService(vo);
        if (!ToolsUtil.isEmpty(entity.getEntity())) {
            if (entity.getEntity() instanceof Page) {
                Page pageList = (Page) entity.getEntity();
                data.put("total", pageList.getCount());
                data.put("rows", pageList.getPageObjects());
            } else {
                List list = (List) entity.getEntity();
                data.put("total", list.size());
                data.put("rows", list);
            }
        } else {
            data.put("total", "0");
        }
        return data;
    }

    /**
     * description:  保存元素信息
     */
    @RequestMapping(value = "/info/saveMetadata", method = RequestMethod.POST)
    @ResponseBody
    public ResultMsg saveMetadata(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        ResultMsg msg = null;
        Map<String, String> params = this.getParameterMap(request);
        params.put("method", "save");
        ParamsVo vo = new ParamsVo();
        vo.setParams(params);
        vo.setMethodKey("metadataAction");
        ResultEntity entity = doInfoService(vo);
        if (StrUtil.isNotNull(String.valueOf(entity.getEntity()))) {
            msg = new ResultMsg("T", String.valueOf(entity.getEntity()));
        } else {
            msg = new ResultMsg("F", entity.getMessage());
        }
        return msg;
    }

    /**
     * description:  删除元素（metadataId,sortId）
     */
    @RequestMapping(value = "/info/delMetadata", method = RequestMethod.GET)
    @ResponseBody
    public ResultMsg delMetadata(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        ResultMsg msg = null;
        Map<String, String> params = this.getParameterMap(request);
        params.put("method", "del");
        ParamsVo vo = new ParamsVo();
        vo.setParams(params);
        vo.setMethodKey("metadataAction");
        ResultEntity entity = doInfoService(vo);
        if (StrUtil.isNotNull(String.valueOf(entity.getEntity()))) {
            msg = new ResultMsg("T", String.valueOf(entity.getEntity()));
        } else {
            msg = new ResultMsg("F", entity.getMessage());
        }
        return msg;
    }

    @RequestMapping(value = "/info/listMetadata", method = RequestMethod.GET)
    @ResponseBody
    public Object listMetadata(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        Map<String, String> params = this.getParameterMap(request);
        Map<String, Object> data = new HashMap<String, Object>();
        params.put("method", "list");
        ParamsVo vo = new ParamsVo();
        vo.setParams(params);
        vo.setMethodKey("metadataAction");
        ResultEntity entity = doInfoService(vo);
        if (ToolsUtil.isEmpty(entity.getEntity())) {
            if (entity.getEntity() instanceof Page) {
                Page pageList = (Page) entity.getEntity();
                data.put("total", pageList.getCount());
                data.put("rows", pageList.getPageObjects());
            } else {
                List list = (List) entity.getEntity();
                data.put("total", list.size());
                data.put("rows", list);
            }
        } else {
            data.put("total", "0");
        }
        return data;
    }

    public void setInfoService(ApiService infoService) {
        this.infoService = infoService;
    }

    protected ResultEntity doInfoService(ParamsVo vo){
        if(null == this.infoService) {
            Object obj = SpringContextLoader.getBean("infoService");
            if (obj != null) {
                this.infoService = (ApiService) obj;
            }
        }
        if(null == this.infoService){
            return LoadRpcService.service().doService("infoService",vo.getMethodKey(),"xml",vo.getParams(),null);
        }else{
            return this.infoService.doService(vo);
        }
    }
}
